#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
依赖安装脚本
自动尝试多个镜像源安装Pillow
"""

import subprocess
import sys
import os

def run_command(cmd):
    """运行命令并返回结果"""
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
        return result.returncode == 0, result.stdout, result.stderr
    except Exception as e:
        return False, "", str(e)

def install_pillow():
    """尝试从多个源安装Pillow"""
    sources = [
        ("官方PyPI", "pip install --index-url https://pypi.org/simple/ Pillow"),
        ("阿里云镜像", "pip install -i https://mirrors.aliyun.com/pypi/simple/ Pillow"),
        ("豆瓣镜像", "pip install -i https://pypi.douban.com/simple/ Pillow"),
        ("清华大学镜像", "pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ Pillow"),
        ("中科大镜像", "pip install -i https://pypi.mirrors.ustc.edu.cn/simple/ Pillow"),
    ]
    
    print("正在尝试安装Pillow...")
    print("=" * 50)
    
    for name, cmd in sources:
        print(f"\n尝试使用 {name} 安装...")
        success, stdout, stderr = run_command(cmd)
        
        if success:
            print(f"✅ {name} 安装成功!")
            print(stdout)
            return True
        else:
            print(f"❌ {name} 安装失败")
            if stderr:
                print(f"错误信息: {stderr}")
    
    print("\n❌ 所有镜像源都安装失败")
    print("\n请尝试以下解决方案:")
    print("1. 检查网络连接")
    print("2. 关闭代理设置")
    print("3. 使用VPN")
    print("4. 手动下载Pillow wheel文件")
    
    return False

def check_pillow():
    """检查Pillow是否已安装"""
    try:
        import PIL
        print(f"✅ Pillow已安装，版本: {PIL.__version__}")
        return True
    except ImportError:
        print("❌ Pillow未安装")
        return False

def main():
    """主函数"""
    print("YOLO标注工具 - 依赖检查与安装")
    print("=" * 50)
    
    # 检查是否已安装
    if check_pillow():
        print("\n🎉 依赖已满足，可以直接运行程序!")
        print("运行命令: python yolo_annotator.py")
        return
    
    # 尝试安装
    if install_pillow():
        print("\n🎉 安装完成，可以运行程序了!")
        print("运行命令: python yolo_annotator.py")
    else:
        print("\n💡 如果安装仍然失败，请尝试:")
        print("1. 更新pip: python -m pip install --upgrade pip")
        print("2. 使用conda: conda install pillow")
        print("3. 手动下载安装包")

if __name__ == "__main__":
    main()
